<!-- pages/index/user.vue -->
<template>
    <s-layout
            title="我的"
            tabbar="/pages/index/user"
            navbar="custom"
            :bgStyle="template.page"
            :navbarStyle="template.navigationBar"
            onShareAppMessage
    >
        <!-- 页面模块循环渲染 -->
        <s-block
                v-for="(item, index) in template.components"
                :key="index"
                :styles="item.property.style"
        >
            <s-block-item :type="item.id" :data="item.property" :styles="item.property.style" />
        </s-block>

        <!-- 登录后显示订阅按钮 -->
        <view v-if="userInfo.nickname" class="subscribe-box">
            <view class="subscribe-btn" @click="onSubscribeMessage">
                开启消息提醒
            </view>
        </view>

        <!-- 未登录状态提示 -->
        <view v-else class="login-tips">
            请先登录后使用订阅提醒功能
        </view>
    </s-layout>
</template>

<script setup>
import { computed } from 'vue'
import { onShow, onPageScroll, onPullDownRefresh } from '@dcloudio/uni-app'
import sheep from '@/sheep'
import { WxaSubscribeTemplate } from '@/sheep/helper/const'

// 隐藏原生 tabBar
uni.hideTabBar({ fail: () => {} })

// 页面模板
const template = computed(() => sheep.$store('app').template.user)

// 用户信息
const userInfo = computed(() => sheep.$store('user').userInfo)

// 监听页面显示
onShow(() => {
    sheep.$store('user').updateUserData()
})

// 下拉刷新
onPullDownRefresh(() => {
    sheep.$store('user').updateUserData()
    setTimeout(() => uni.stopPullDownRefresh(), 800)
})

// 页面滚动
onPageScroll(() => {})

/**
 * 点击订阅按钮
 * 仅在用户已登录 && 微信小程序端执行
 */
const onSubscribeMessage = async () => {
    console.log(userInfo.value)
    if (!userInfo.value.nickname) {
        uni.showToast({
            title: '请先登录后再开启提醒',
            icon: 'none'
        })
        return
    }

    // #ifdef MP-WEIXIN
    try {
        const provider = sheep.$platform.useProvider('wechat')
        await provider.subscribeMessage([
            WxaSubscribeTemplate.WXA_ORDER_APPOINTMENT_TRANSACTION_COMPLETE,
            WxaSubscribeTemplate.WXA_ORDER_APPOINTMENT_PRODUCTION_COMPLETE,
            WxaSubscribeTemplate.WXA_ORDER_APPOINTMENT_AUDIT_REJECT
        ])
        uni.showToast({
            title: '订阅成功',
            icon: 'success'
        })
    } catch (err) {
        console.error('订阅消息失败:', err)
        uni.showToast({
            title: '订阅失败或已拒绝',
            icon: 'none'
        })
    }
    // #endif

    // #ifndef MP-WEIXIN
    uni.showToast({
        title: '当前端不支持订阅消息',
        icon: 'none'
    })
    // #endif
}
</script>

<style lang="scss">
.subscribe-box {
  margin: 40rpx auto;
  display: flex;
  justify-content: center;
}

.subscribe-btn {
  color: #007aff;
}

.login-tips {
  text-align: center;
  color: #999;
  margin-top: 40rpx;
  font-size: 26rpx;
}
</style>
